package com.software.myopiachildren.ui.login;


import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.software.myopiachildren.App;
import com.software.myopiachildren.MainActivity;
import com.software.myopiachildren.R;
import com.software.myopiachildren.base.BaseActivity;
import com.software.myopiachildren.bean.BaseInfo;
import com.software.myopiachildren.bean.LoginInfo;
import com.software.myopiachildren.content.Constant;
import com.software.myopiachildren.http.HostType;
import com.software.myopiachildren.http.HttpApi2;
import com.software.myopiachildren.utils.RegexUtils;
import com.software.myopiachildren.utils.ToastUtil;
import com.software.myopiachildren.utils.perm.NetworkUtils;
import com.software.myopiachildren.utils.sp.SP;
import com.umeng.analytics.MobclickAgent;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * 绑定手机页
 *
 * @author penglei
 * @date 2020/05/12
 */
public class BindPhoneActivity extends BaseActivity {
    private static final String TAG = "BindPhoneActivity";

    @BindView(R.id.iv_title_left)
    ImageView mIvTitleLeft;
    @BindView(R.id.tv_title_text)
    TextView mTvTitleText;
    @BindView(R.id.tv_title_right)
    TextView mTvTitleRight;
    @BindView(R.id.lay_title_home)
    LinearLayout mLayTitleHome;

    @BindView(R.id.et_bind_phone)
    EditText mEtBindPhone;
    @BindView(R.id.et_bind_code)
    EditText mEtBindCode;
    @BindView(R.id.btn_bind_get_code)
    Button mBtnBindGetCode;
    @BindView(R.id.btn_bind)
    Button mBtnBind;


    private String account;
    private String code;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_bind_phone;
    }

    @Override
    public void initView() {
        mTvTitleText.setText(getResources().getString(R.string.s_bind_phone));
    }

    @Override
    public void initData() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @OnClick({R.id.iv_title_left, R.id.btn_bind_get_code, R.id.btn_bind})
    public void onClick(final View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;

            case R.id.btn_bind_get_code:
                getCode();
                break;

            case R.id.btn_bind:
                getBind();
                break;
        }
    }


    /**
     * 获取验证码
     */
    private void getCode() {
        account = mEtBindPhone.getText().toString().trim();
        if (TextUtils.isEmpty(account)) {
            ToastUtil.showShort(getString(R.string.toast_phone_empty));
            return;
        }
        if (!RegexUtils.checkEmail(account)) {
            ToastUtil.showShort(getString(R.string.toast_phone_error));
            return;
        }

        if (NetworkUtils.isConnected(BindPhoneActivity.this)) {
            Map<String, String> params = new HashMap<>();
            params.put("account", account);
            params.put("yzm_type", 3 + "");

            HttpApi2.getApiService(HostType.TELE_CONFIG).getCode(params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    startCountDown();
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }

    }


    /**
     * 绑定
     */
    private void getBind() {
        account = mEtBindPhone.getText().toString().trim();
        code = mEtBindCode.getText().toString().trim();

        //验证手机号
        if (TextUtils.isEmpty(account)) {
            ToastUtil.showShort(getString(R.string.toast_phone_empty));
            return;
        }
        if (!RegexUtils.checkTelephone(account)) {
            ToastUtil.showShort(getString(R.string.toast_phone_error));
            return;
        }

        //验证验证码
        if (TextUtils.isEmpty(code)) {
            ToastUtil.showShort(getString(R.string.toast_verifycode_empty));
            return;
        }
        if (code.length() < 3 || code.length() > 6) {
            ToastUtil.showShort(getString(R.string.toast_verifycode_error));
            return;
        }

        if (NetworkUtils.isConnected(BindPhoneActivity.this)) {
            Map<String, String> params = new HashMap<>();
            params.put("account", account);
            params.put("code", code);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getBindMobile(params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<LoginInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(LoginInfo loginInfo) {
                            try {
                                Log.e(TAG, "===loginInfo:" + loginInfo.toString());
                                if (loginInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    App.user = loginInfo.getData(); // 用户参数
                                    new SP().save(Constant.USER_NAME, loginInfo.getData().getNickname());
                                    new SP().save(Constant.SP_USER_DATA, new Gson().toJson(loginInfo.getData()));
                                    startActivity(new Intent(BindPhoneActivity.this, MainActivity.class));
                                    MobclickAgent.onEvent(BindPhoneActivity.this, "register"); // 注册事件ID
                                    finish();
                                } else {
                                    ToastUtil.showShort(loginInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }

    }


    /**
     * 计时器
     */
    public void startCountDown() {
        ToastUtil.showShort(getString(R.string.toast_code_already));
        mBtnBindGetCode.setEnabled(false);
        mVerificationTimer.start();
    }

    /**
     * 定时器
     */
    private CountDownTimer mVerificationTimer = new CountDownTimer(60 * 1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (mBtnBindGetCode != null) {
                mBtnBindGetCode.setEnabled(false);
                mBtnBindGetCode.setText(getString(R.string.toast_code_cd, millisUntilFinished / 1000));
            }
        }

        @Override
        public void onFinish() {
            if (mBtnBindGetCode != null) {
                mBtnBindGetCode.setEnabled(true);
                mBtnBindGetCode.setText(getString(R.string.s_register_get_code));
            }
        }
    };


}
